package com.tunnel.service.hendler;

import com.tunnel.common.protocol.Protocol;
import com.tunnel.common.protocol.ProtocolType;
import com.tunnel.service.cache.ResultCache;
import com.tunnel.service.proxy.ProxyService;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 处理和客户端之间的数据交互
 */
public class TunnelHandler extends SimpleChannelInboundHandler<Protocol> {


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        String channelId = ctx.channel().id().asLongText();
        System.out.println(channelId + "加入");
    }
    //断开连接, 将xx客户离开信息推送给当前在线的客户，该方法会自动将channel从channelGroup删除
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        String channelId = ctx.channel().id().asLongText();
        System.out.println(channelId + "离开");
    }
    //表示channel 处于活动状态, 提示 xx上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String channelId = ctx.channel().id().asLongText();
        System.out.println(channelId + "上线");
    }

    //表示channel 处于不活动状态, 提示 xx离线了
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String channelId = ctx.channel().id().asLongText();
        System.out.println(channelId + "离线");
    }
    //读取数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Protocol msg) throws Exception {
        // 操作指令，定义命令类型，1：注册，2：心跳，3：数据传输，4：关闭
        int opsType = msg.getCommonType();
        switch (opsType) {
            case ProtocolType.REGISTER:
                ProxyService.registerClient(ctx,  msg);
                break;
            case ProtocolType.HEARTBEAT:
                ProxyService.heartbeat(ctx,  msg);
                break;
            case ProtocolType.TRANSFER:
                System.out.println("数据传输");
                ResultCache.resMap.put(msg.getSequenceId(), msg);
                break;
            case ProtocolType.CLOSE:
                System.out.println("客户端关闭");
                break;
        }

    }

    // 发生异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.close();
    }
}

